<?php

namespace App\Admin\Actions\Get;

use App\Models\Product;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;

class Destory extends RowAction
{
    public $name = '删除';

    public function handle(Model $model)
    {
        $pid = $this->getKey();
        $sonsNum = $model->where('pid', $pid)->count();

        if ($sonsNum > 0) {
            return $this->response()->error('请先删除下级分类')->refresh();
        } else {
            $productsNum = Product::where('category_id', $pid)->count();
            if ($productsNum > 0) {
                return $this->response()->error('请先删除该分类下的商品')->refresh();
            } else {
                $model->where('id', $pid)->delete();
                return $this->response()->success('Success message.')->refresh();
            }
        }

    }

    public function dialog()
    {
        $this->confirm('确定删除吗？');
    }

}